import argparse
import hashlib
import json
import os
from urllib import parse

import pandas as pd
import requests
import tqdm

from args import get_args_parser
from tools.BDgetGPS.CSVloader import get_list

OP_FILE = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), 'DATA', 'OP_1.csv')


def get_sn(args, pa):
    query = pa["query"]
    region = pa["region"]
    city_limit = pa["city_limit"]
    output = pa["output"]
    coord_type = pa["coord_type"]
    queryStr = '/place/v2/search?query={}&tag=ATM&region={}&city_limit={}&output={}&coord_type={}&ak={}'.format(query,
                                                                                                                region,
                                                                                                                city_limit,
                                                                                                                output,
                                                                                                                coord_type,
                                                                                                                args.MAP_AK,
                                                                                                                )
    encoderStr = parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    rawStr = encoderStr + args.MAP_SK
    sn = (hashlib.md5(parse.quote_plus(rawStr).encode("utf8")).hexdigest())
    url = parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
    return sn, url


def get_GPS(args, loc, is_all=False):
    _pa = {"tag": "ATM", "region": "珠海", "city_limit": True, "output": "json", "coord_type": 1, "ak": args.MAP_AK,
           "query": loc}
    My_SN, url = get_sn(args, _pa)
    headers = {
        'User-Agent': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)"}
    r = requests.get(url, headers=headers)
    decoderJson = json.loads(r.text)

    if decoderJson['status'] != 0:
        print("服务器没有成功返回")
        return False
    elif len(decoderJson["results"]) == 0:
        print("返回0个地址")
        return False
    elif is_all == False:
        data = decoderJson["results"][0]["location"]
        return data["lat"], data["lng"]
    else:
        data = []
        data_list = decoderJson["results"]
        for result in data_list:
            location = result['location']
            data.append([location['lat'], location['lng']])
        return data


def saveData(Data, f_path):
    df = pd.DataFrame(Data)
    df.to_csv(f_path, index=False)


def run(args, fpath=None):
    if fpath is None:
        fpath = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), 'DATA', 'device_info_1.csv')
    try:
        data = get_list(fpath)
    except:
        print("文件读取错误")
        return
    lat_list = []
    lng_list = []
    for loc in tqdm.tqdm(data['地址']):
        try:
            lat, lng = get_GPS(args, loc)
        except:
            print("位置{}读取坐标失败".format(loc))
            lat = None
            lng = None
        lat_list.append(lat)
        lng_list.append(lng)
    Data = {
        "编号": data['编号'],
        "型号": data['型号'],
        "地址": data['地址'],
        "纬度": lat_list,
        "经度": lng_list,
    }
    saveData(Data, OP_FILE)


if __name__ == '__main__':
    parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])
    args = parser.parse_args()
    run(args, os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), 'DATA', 'device_info_1.csv'))
